package cn.hd01.service.impl;

import cn.hd01.repository.CarRepository;
import cn.hd01.repository.entity.Car;
import cn.hd01.service.CarService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cyb
 * @date 2017/5/31.
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car, Integer> implements CarService {

    private final CarRepository repository;

    public CarServiceImpl(CarRepository repository) {
        super(repository);
        this.repository = repository;
    }

    @Override
    public Page<Car> findAll(final Car car, Pageable pageable) {
        if (car == null) {
            return repository.findAll(pageable);
        }

        return repository.findAll(Specifications.where(new Specification<Car>() {
            @Override
            public Predicate toPredicate(Root<Car> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (null != car.getAuthorId()) {
                    predicates.add(cb.equal(r.get("authorId").as(Integer.class), car.getAuthorId()));
                }

                return cb.and(predicates.toArray(new Predicate[0]));
            }
        }), pageable);
    }
}
